package cmd

import (
	"os"
	"os/signal"
	"syscall"
	"time"

	"fsd/api"
	"fsd/fight"
	"fsd/impl"
	"fsd/logger"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
)

var srvCmd = &cobra.Command{
	Use:   "srv",
	Short: "start server",
	Long:  "start server",
	Run:   startServer,
}

func init() {
	rootCmd.AddCommand(srvCmd)
}

func startServer(cmd *cobra.Command, args []string) {
	logger.InitLogger(cfgData.Server.LogEnv, cfgData.Server.LogLevel, cfgData.Server.LogPath)

	logger.Info("start server")
	logger.Debug("server address", zap.String("", cfgData.Server.LAddr))
	initFightServerConfig()
	fight.ListenAndServe()
	api.Start(cfgData.Api.LAddr)
	logger.Info("start server ok")

	trapOSExitSignal()
	os.Exit(0)
}

func initFightServerConfig() {
	fight.Srv.GameProtocoler = &impl.GameProtocol{}
	fight.Srv.Config = &fight.Config{
		Addr:                cfgData.Server.LAddr,
		RecvNetChanSize:     128,
		SendNetChanSize:     128,
		GetGameChanSize:     128,
		PutGameChanSize:     128,
		ConnReadTimeout:     10 * time.Second,
		ConnWriteTimeout:    10 * time.Second,
		GameTickerTime:      30 * time.Second,
		GameRoundTime:       cfgData.Server.GameRoundMS * int64(time.Millisecond),
		GameSettleTime:      2 * time.Second,
		GameAllCmdsSize:     36000,
	}
}

func trapOSExitSignal() {
	var gracefulStop = make(chan os.Signal)
	signal.Notify(gracefulStop, syscall.SIGTERM, syscall.SIGINT)
	sig := <-gracefulStop
	logger.Info("trap os signal", zap.Any("sig", sig))
	fight.TrapDoStop()
	logger.Info("Server exiting")
}
